# coding=utf-8
"""
Copyright (c) Huawei Technologies Co., Ltd. 2020-2028. All rights reserved.
Description:
FileName：start.py
Author: h00568282/huangbin
Create Date: 2025/9/18 16:52
Notes:

"""
import json
from datetime import datetime

import rich.console as console

from sys_intd.commands.utils.agent_utils import ApiClient, BASE_URL, create_mcp_server, \
    comb_create, delete_agent_api
from sys_intd.manager import McpServerManager
from sys_intd.manager.agent_manager import AgentManager
from sys_intd.schema import AgentConfig

console = console.Console()

json_str = '''{
    "name": "name",
    "overview": "overview",
    "description": "description",
    "mcpType": "sse",
    "author": "root",
    "config": {
        "env": {},
        "autoApprove": [],
        "disabled": false,
        "auto_install": false,
        "description": "",
        "timeout": 60,
        "url": "url"
    }
}'''

com_json_str = '''{
  "appType": "agent",
  "icon": "", 
  "name": "agent_comb",  
  "description": "测试agent comb", 
  "dialogRounds": 3, 
  "permission": {  
    "visibility": "public",
    "authorizedUsers": []
  },
  "workflows": [], 
  "mcpService": [],
  "published": "True"
}'''


def create_agent(server_names: str, agent_name: str | None = None):
    output_lines = []
    # 查询是否已安装server_name
    server_list = [s.strip() for s in server_names.split(',') if s.strip()]
    service_ids = []
    api_client = ApiClient(BASE_URL)
    agent_manager = AgentManager()

    # 验证mcp列表不为空
    if not server_list:
        error_msg = "[bold red]create agent error: 验证mcp列表不为空[/]"
        output_lines.append(error_msg)
        console.print(error_msg)
        return output_lines

    # 检查agent名称是否已存在
    if agent_name and agent_manager.get_agent(agent_name):
        error_msg = f"[bold red]create agent error: {agent_name} 已存在,请先删除[/]"
        output_lines.append(error_msg)
        console.print(error_msg)
        return output_lines

    mcp_server_manager = McpServerManager()
    for server_name in server_list:
        status_msg = f"[blue]正在处理mcp: {server_name}[/]"
        output_lines.append(status_msg)
        console.print(status_msg)

        server_metadata = mcp_server_manager.get_mcp_metadata(server_name)
        if not server_metadata:
            error_msg = f"[bold red]create agent error: {server_name} 不存在或未安装[/]"
            output_lines.append(error_msg)
            console.print(error_msg)
            return output_lines

        name = server_metadata['name']
        overview = server_metadata['overview']
        description = server_metadata['description']
        url = server_metadata['config']['url']
        data = json.loads(json_str)
        if agent_name is None:
            data["name"] = name
        else:
            data["name"] = agent_name
        data["overview"] = overview
        data["description"] = description
        data["config"]["url"] = url
        console.print("即将进行mcp安装的配置信息如下：")
        console.print(json.dumps(data, indent=4, ensure_ascii=False))
        service_id = create_mcp_server(api_client, data)
        service_ids.append(service_id)
        console.print(f"[green]成功创建MCP服务，ID: {service_id} name: {server_name}[/]")
    com_data = json.loads(com_json_str)
    com_data.update({
        'name': agent_name,
        'description': f"智能体: {', '.join(server_list)}",
        'mcpService': service_ids
    })
    console.print("[blue]即将创建的agent组合信息如下：[/]")
    console.print(json.dumps(com_data, indent=4, ensure_ascii=False))
    comb_id = comb_create(api_client, com_data)
    if not comb_id:
        error_msg = "[bold red]create agent error: 智能体创建失败，未返回ID[/]"
        output_lines.append(error_msg)
        console.print(error_msg)
        return output_lines
    console.print(f"[green]组合智能体创建成功，ID: {comb_id}[/]")

    current_time = datetime.now().replace(microsecond=0)
    new_agent = AgentConfig(
        id=comb_id,
        name=agent_name,
        create_time=current_time,
        mcp_list=server_list,
        service_ids=service_ids,
    )
    agent_manager.add_agent(new_agent)

    success_msg = f"[bold green]create agent: {agent_name} 成功[/]"
    output_lines.append(success_msg)
    console.print(success_msg)

    return output_lines


def delete_agent(agent_name: str):
    """删除指定agent"""
    output_lines = []
    agent_manager = AgentManager()
    agent = agent_manager.get_agent(agent_name)

    if not agent:
        message = f"[bold red]删除失败: agent {agent_name} 不存在[/]"
        output_lines.append(message)
        console.print(message)
        return output_lines

    # 初始化API客户端并执行删除操作
    api_client = ApiClient(BASE_URL)
    try:
        # 调用API删除远程资源
        console.print(f"[blue]正在删除远程agent服务: {agent_name} (ID: {agent.id})[/]")
        response = delete_agent_api(api_client, agent.id)
        console.print("result = ", response)
        # 判断API删除是否成功
        if response and isinstance(response, dict):
            # 检查返回的appId是否与请求的一致
            if response.get("result").get("appId") == agent.id:
                success_msg = f"[green]远程agent服务 {agent_name} 删除成功[/]"
                output_lines.append(success_msg)
                console.print(success_msg)

                # 远程删除成功后，删除本地配置
                if agent_manager.delete_agent(agent_name):
                    local_success = f"[bold green]本地配置中 {agent_name} 删除成功[/]"
                    output_lines.append(local_success)
                    console.print(local_success)
                else:
                    local_error = f"[bold yellow]警告: 远程删除成功，但本地配置 {agent_name} 删除失败[/]"
                    output_lines.append(local_error)
                    console.print(local_error)
            else:
                mismatch_msg = f"[bold red]删除失败: 远程返回的ID与请求不一致[/]"
                output_lines.append(mismatch_msg)
                console.print(mismatch_msg)
        else:
            api_error = f"[bold red]删除失败: 远程API返回无效结果[/]"
            output_lines.append(api_error)
            console.print(api_error)

    except RuntimeError as e:
        # 捕获delete_agent_api抛出的运行时错误
        error_msg = f"[bold red]删除失败: {str(e)}[/]"
        output_lines.append(error_msg)
        console.print(error_msg)
    except Exception as e:
        # 捕获其他未预料的错误
        unexpected_error = f"[bold red]删除过程发生意外错误: {str(e)}[/]"
        output_lines.append(unexpected_error)
        console.print(unexpected_error)

    return output_lines


def search_agent(agent_name: str):
    """搜索指定agent"""
    output_lines = []
    agent_manager = AgentManager()
    agent = agent_manager.get_agent(agent_name)

    if agent:
        message = f"[bold green]找到agent: {agent_name}[/]"
        output_lines.append(message)
        console.print(message)

        details = [
            f"ID: {agent.id}",
            f"创建时间: {agent.create_time}",
            f"关联MCP服务: {', '.join(agent.mcp_list)}",
            f"服务ID列表: {', '.join(agent.service_ids)}"
        ]
        output_lines.extend(details)
        for line in details:
            console.print(line)
    else:
        # 搜索相似名称的agent
        all_agents = agent_manager.list_agents()
        similar_agents = [a for a in all_agents if agent_name in a.name]

        if similar_agents:
            message = f"[bold yellow]未找到 {agent_name}，但找到相似的agent:[/]"
            output_lines.append(message)
            console.print(message)

            for a in similar_agents:
                line = f"- {a.name}"
                output_lines.append(line)
                console.print(line)
        else:
            message = f"[bold red]未找到agent {agent_name}[/]"
            output_lines.append(message)
            console.print(message)

    return output_lines


def list_agent():
    """列出所有已创建的agents"""
    agent_manager = AgentManager()
    agents = agent_manager.list_agents()
    output_lines = []

    if not agents:
        message = "[yellow]没有找到任何agent[/]"
        output_lines.append(message)
        console.print(message)
        return output_lines

    title = "[bold green]所有agents列表:[/]"
    output_lines.append(title)
    console.print(title)

    for agent in agents:
        # 收集带颜色标记的信息到输出列表
        output_lines.append(f"[blue]名称:[/] {agent.name}")
        output_lines.append(f"[blue]ID:[/] {agent.id}")
        output_lines.append(f"[blue]创建时间:[/] {agent.create_time}")
        output_lines.append(f"[blue]关联MCP服务:[/] {', '.join(agent.mcp_list)}")
        output_lines.append("---")

        # 控制台输出（与列表内容一致）
        console.print(f"[blue]名称:[/] {agent.name}")
        console.print(f"[blue]ID:[/] {agent.id}")
        console.print(f"[blue]创建时间:[/] {agent.create_time}")
        console.print(f"[blue]关联MCP服务:[/] {', '.join(agent.mcp_list)}")
        console.print("---")

    return output_lines
